package testHibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import domain.Student;

public class TestHibernate {
	private static SessionFactory sf;
	@BeforeClass//加载类之前
	public static void beforeClass(){
		sf=new AnnotationConfiguration().configure().buildSessionFactory();
	}
	@Test
	public void testSchemaExport(){
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);//建表语句打不打印，自动建表否
	}
	@Test
	public void testSave(){
		//一定要自己写出无参
		Student stu = new Student("hej",20);
		Student stu1 = new Student("liul",24);
		Session s = sf.openSession();
		s.beginTransaction();
		s.save(stu);
		s.save(stu1);
		s.getTransaction().commit();
	}
	@Test
	public void testHQL(){
		Session s = sf.openSession();
		//Student 为类名
		String hql="from Student";//select * from student
		String hql1="from Student s where s.id=3";
		List<Student> studendts = s.createQuery(hql).list();
		Iterator<Student> studentz=s.createQuery(hql).iterate();
		for (Student stu : studendts) {
			System.out.println(stu.getName());
		}
	}
	@Test
	public void testGet(){
		Session s = sf.openSession();
		s.beginTransaction();
		Student stu = (Student) s.get(Student.class, 1);
		s.getTransaction().commit();
		System.out.println(stu.getName());
	}
	@Test
	public void testUpdate(){
		Session s = sf.openSession();
		s.beginTransaction();
		Student stu = (Student) s.get(Student.class, 1);
		stu.setAge(80);
		stu.setName("qiangre");
		s.update(stu);//根据主键id
		stu=(Student) s.get(Student.class, 1);//load get两个方法的区别
		//Student stu2=(Student)s.load(Student.class, 1);
		s.update(stu);
		s.getTransaction().commit();//自动调用s.close();
		System.out.println(stu.getName());
	}
	@Test
	public void testDelete(){
		Session s = sf.openSession();
		s.beginTransaction();
		Student stu = (Student) s.get(Student.class, 1);
		s.delete(stu);//根据主键id
		s.getTransaction().commit();
	}
	@AfterClass//类不存在时
	public static void afterClass(){
		sf.close();
	}
}
